package com.sc.outpatientsys.service.impl;

import com.sc.outpatientsys.entity.Admin;
import com.sc.outpatientsys.mapper.AdminMapper;
import com.sc.outpatientsys.service.IAdminService;
import com.sc.outpatientsys.service.ex.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Slf4j
@Service
public class AdminServiceImpl implements IAdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Override
    public void reg(Admin admin) {
        String username = admin.getUserName();
        Admin res = adminMapper.findAdminByName(username);
        if(res != null){
            throw new UserNameHasExistException("用户名已经存在");
        }
        Integer rows = adminMapper.insertAdmin(admin);
        if(rows!=1){
            throw new InsertException("用户注册时出现未知错误");
        }
    }

    @Override
    public Admin login(String userName, String password) {
        log.info(userName+" :: "+password);
        Admin admin = adminMapper.findAdminByName(userName);
//        log.info(admin.toString()+" ");
        if(admin != null && password.equals(admin.getPassword())){
            return admin;
        }
        else{
            throw new PasswordNotMacthException("用户名密码错误");
        }
    }

    @Override
    public void update(Admin admin) {
        Integer res = adminMapper.updateAdmin(admin);
        if(res!=1){
            throw new UpdateException("修改时发生错误");
        }
    }

    @Override
    public void delete(int ad_ID) {
        Integer res = adminMapper.deleteAdmin(ad_ID);
        if(res!=1){
            throw new DeleteException("删除时发生错误");
        }
    }

    @Override
    public Admin findById(int ad_ID) {
        Admin admin = adminMapper.findAdminByID(ad_ID);
        if(admin==null){
            throw new NotFindException("未找到");
        }
        return admin;
    }

    @Override
    public Admin findByName(String username) {
        Admin admin = adminMapper.findAdminByName(username);
        if(admin ==null){
            throw new NotFindException("未找到");
        }
        return admin;
    }

    @Override
    public List<Admin> findAll() {
        List<Admin> admins = adminMapper.selectAllAdmin();
        if(admins == null){
            throw  new NotFindException("未找到");
        }
        return admins;
    }
}
